//https://leetcode.cn/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/?envType=daily-question&envId=2024-04-04


class Solution {
public:
    vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges) {
        vector<int> e[n];
        for (auto &ei: edges)
            e[ei[1]].push_back(ei[0]);
        vector<vector<int>> res(n);
        vector<int> vis(n, -1);
        for (int i = 0; i < n; i++) {
            queue<int> q;
            vis[i] = i;
            q.push(i);
            while (!q.empty()) {
                int t = q.front();
                q.pop();
                for (auto j: e[t])
                    if (vis[j] != i) {
                        vis[j] = i;
                        q.push(j);
                    }
            }
            for (int j = 0; j < n; j++)
                if (vis[j] == i && j != i)
                    res[i].push_back(j);
        }
        return res;
    }
};